package com.hqq.handler;

import com.hqq.config.NettyConfig;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * WebSocket请求处理业务类
 * Created by heqianqian on 2018/2/4.
 */
public class MyWebSocketHandler extends SimpleChannelInboundHandler<Object> {
    private static final Logger LOGGER = LoggerFactory.getLogger(MyWebSocketHandler.class);

    private static final String WEB_SOCKET_URL = "ws://localhost:8888/websocket";

    private WebSocketServerHandshaker handshaker;

    /**
     * 连接建立
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        NettyConfig.channelGroup.add(ctx.channel());
        LOGGER.debug("===连接建立===");
    }

    /**
     * 断开连接
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        NettyConfig.channelGroup.remove(ctx.channel());
        LOGGER.debug("===连接断开===");
    }

    /**
     * 接收数据结束后
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        LOGGER.error("===连接异常==:", cause);
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object msg) throws Exception {
        if (msg instanceof FullHttpRequest) {
            //http请求
            handleHttpRequest(channelHandlerContext, (FullHttpRequest) msg);
        } else if (msg instanceof WebSocketFrame) {
            //websocket请求
            handleWebSocketFrame(channelHandlerContext, (WebSocketFrame) msg);
        }
    }

    /**
     * 处理websocket请求
     *
     * @param channelHandlerContext
     * @param frame
     */
    private void handleWebSocketFrame(ChannelHandlerContext channelHandlerContext, WebSocketFrame frame) {
        if (frame instanceof CloseWebSocketFrame) { //关闭请求
            handshaker.close(channelHandlerContext.channel(), (CloseWebSocketFrame) frame);
        }
        if (frame instanceof PingWebSocketFrame) {//ping请求
            channelHandlerContext.channel().write(new PongWebSocketFrame(frame.content()));
            return;
        }
        if (!(frame instanceof TextWebSocketFrame)) {//二进制信息
            LOGGER.debug("===暂时不支持二进制信息===");
            throw new RuntimeException("不支持的信息");
        }
        //返回应答信息
        String request = ((TextWebSocketFrame) frame).text();
        LOGGER.debug("===收到信息===:{}", request);
        TextWebSocketFrame textWebSocketFrame = new TextWebSocketFrame(request);
        //向每个连接的客户端发送应答
        NettyConfig.channelGroup.writeAndFlush(textWebSocketFrame);
    }

    /**
     * 处理http请求
     *
     * @param channelHandlerContext
     * @param request
     */
    private void handleHttpRequest(ChannelHandlerContext channelHandlerContext, FullHttpRequest request) {
        if (!request.getDecoderResult().isSuccess() || !("websocket".equals(request.headers().get("Upgrade")))) {
            sendHttpResponse(channelHandlerContext, request, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
            return;
        }
        WebSocketServerHandshakerFactory factory = new WebSocketServerHandshakerFactory(WEB_SOCKET_URL, null, false);
        handshaker = factory.newHandshaker(request);
        if (null == handshaker) {
            WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(channelHandlerContext.channel());
        } else {
            handshaker.handshake(channelHandlerContext.channel(), request);
        }
    }

    /**
     * 发送http回复
     *
     * @param channelHandlerContext
     * @param request
     * @param response
     */
    private void sendHttpResponse(ChannelHandlerContext channelHandlerContext, FullHttpRequest request, DefaultFullHttpResponse response) {
        if (response.getStatus().code() != 200) {//失败请求
            ByteBuf byteBuf = Unpooled.copiedBuffer(response.getStatus().toString(), CharsetUtil.UTF_8);
            response.content().writeBytes(byteBuf);
            byteBuf.release();
        }
        ChannelFuture future = channelHandlerContext.channel().writeAndFlush(response);
        if (response.getStatus().code() != 200) {
            future.addListener(ChannelFutureListener.CLOSE);
        }
    }
}
